package com.hxd.mall.module.product.home

import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.hxd.mall.R
import com.hxd.mall.base.BaseInjectFragment
import com.hxd.mall.constant.HxdConstants.IntentParamsKeyDefine.product_skuNo
import com.hxd.mall.constant.HxdConstantsRouterPath.Product.path_hxd_product_detail_page
import com.hxd.mall.module.product.home.bean.HomeProductListBean
import com.hxd.mall.module.product.home.bean.HomeTypeBean
import com.hxd.mall.module.product.home.bean.ListBean
import com.hxd.mall.module.product.search.adapter.SearchListAdapter
import com.hxd.mall.utils.local.NavigationUtil.routerNavigation
import com.hxd.mall.utils.local.commodity_click
import com.hxd.mall.utils.local.sendPoint
import com.hxd.mall.utils.open.DataCleanManager
import com.hxd.mall.utils.open.initGridRecyclerView
import com.hxd.mall.utils.open.initRecyclerView
import kotlinx.android.synthetic.main.fragment_hometype_layout.*

/**
 * Create by yinzhengwei on 2019-11-26
 * @Function
 *
 * titleStr 当前页面的title
 * navigationUrl 当前页面中间区域请求的接口
 * productUrl 当前页面商品列表请求的接口
 */
class HomeTypeFragment(var position: Int, var titleStr: String, var navigationUrl: String) : BaseInjectFragment<IHomePresenter>(), IHomeView {

    private var productUrl = ""
    private var mHomeBean: HomeTypeBean? = null
    private var mHomeProductBean: HomeProductListBean? = null
    private var mPageNumber: Int = 1
    private var pageSize: Int = 20
    private var doubleAdapter = ProductListAdapter()
    private var singleLineAdapter = SearchListAdapter(R.layout.adapter_active_list_item_layout)
    private var topSingleView: HomeTopView? = null
    private var topDoubleView: HomeTopView? = null
    private var singleLine = true
    private var mView: View? = null

    override fun attachLayoutRes(): Int = R.layout.fragment_hometype_layout

    override fun initViews() {

        initView()
        initListener()

        if (position == 0)
            loadData(true)

        mView = View.inflate(activity, R.layout.no_date_layout, null)
    }

    override fun initData() {}

    private fun loadData(isRefresh: Boolean) {
        if (isRefresh) {
            //当页面回来后滑到顶部然后下拉刷新
            (if (singleLine) productList_single_line else productList_double_line).scrollToPosition(0)
            mPageNumber = 1
        }
        mPresenter?.getProductStateData(navigationUrl)
    }

    override fun finishRefresh() {
        smartRefreshLayout?.finishRefresh()
        smartRefreshLayout?.finishLoadMore()
    }

    override fun finishFailRefresh() {
        smartRefreshLayout?.finishRefresh()
        (if (singleLine) singleLineAdapter else doubleAdapter)?.loadMoreFail()
    }

    //初始化商品布局
    private fun refreshListView() {
        //先清除缓存
        DataCleanManager.clearCache(activity, 100)

        mHomeProductBean?.data?.list?.run {
            if (mPageNumber == 1) {
                if (singleLine) {
                    //如果是单列则清空双列数据
                    reFreshList(false, this, mutableListOf())
                } else {
                    //如果是双列则清空单列数据
                    reFreshList(false, mutableListOf(), this)
                }
            } else {
                if (singleLine) {
                    //如果是单列则清空双列数据
                    reFreshList(true, this, mutableListOf())
                } else {
                    //如果是双列则清空单列数据
                    reFreshList(true, mutableListOf(), this)
                }
            }

            (if (singleLine) singleLineAdapter else doubleAdapter).removeAllFooterView()
            if (mHomeProductBean?.data?.isLastPage == true) {
                (if (singleLine) singleLineAdapter else doubleAdapter).addFooterView(mView)
//                layout_no_data.visibility = View.VISIBLE
                smartRefreshLayout.setEnableLoadMore(false)
            } else {
//                layout_no_data.visibility = View.GONE
                (if (singleLine) singleLineAdapter else doubleAdapter).removeFooterView(mView)
                smartRefreshLayout.setEnableLoadMore(true)
            }
        }
    }

    private fun initView() {
        productList_single_line.initRecyclerView(singleLineAdapter, padding = 0, leftPadding = 116)

        productList_double_line.initGridRecyclerView(doubleAdapter)
        (productList_double_line.layoutManager as GridLayoutManager).spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                // 如果是Header、Footer的对象则占据spanCount的位置，否则就只占用1个位置
                return if (position == 0) 2 else 1
            }
        }
    }

    //点击监听
    private fun initListener() {
        smartRefreshLayout.setOnRefreshListener {
            loadData(true)
        }

        smartRefreshLayout.setOnLoadMoreListener {
            mPageNumber++
            //刷行商品列表
            mPresenter?.getProductListData(productUrl, mPageNumber, pageSize)
        }
        setOnItemListener(singleLineAdapter)
        setOnItemListener(doubleAdapter)
    }

    override fun setMenuVisibility(menuVisible: Boolean) {
        if (menuVisible && smartRefreshLayout != null) {
            if (mHomeBean == null || mHomeProductBean == null) {
                loadData(true)
            }
        }

        //不可见的时候停止banner的滑动
        if (topSingleView != null) {
            (if (singleLine) topSingleView else topDoubleView)?.banner(!userVisibleHint)
        }
    }

    override fun netHomeData(t: HomeTypeBean) {
        if(null == productList_single_line) return
        mHomeBean = t
        singleLine = mHomeBean?.data?.productLayout?.resources?.get(0)?.ext?.singleLine ?: true
        //添加默认的Header
        if (topSingleView == null) {
            context?.run {
                topSingleView = HomeTopView(this, singleLine)
                singleLineAdapter.addHeaderView(topSingleView)
                productList_single_line.adapter = singleLineAdapter

                topDoubleView = HomeTopView(this, singleLine)
                doubleAdapter.addHeaderView(topDoubleView)
                productList_double_line.adapter = doubleAdapter
            }
        }

        //刷新header
        topSingleView?.reLoad(t)
        topDoubleView?.reLoad(t)

        //刷新商品列表,暂时接口地址为了统一bean，放在了resources里
        mHomeBean?.data?.productLayout?.resources?.run {
            if (this.isNotEmpty()) {
                if (singleLine) {
                    productList_single_line?.visibility = View.VISIBLE

                    //如果是单列则将隐藏双列view
                    productList_double_line?.visibility = View.GONE
                } else {
                    //如果是双列则将隐藏单列view
                    productList_single_line?.visibility = View.GONE

                    productList_double_line?.visibility = View.VISIBLE
                }

                productUrl = get(0).entryUri ?: ""
                //刷新商品列表
                mPresenter?.getProductListData(productUrl, mPageNumber, pageSize)
            }
        }
    }

    //商品返回数据
    override fun getProductList(t: HomeProductListBean) {
        mHomeProductBean = t
        refreshListView()
    }

    private fun reFreshList(isAdd: Boolean, listSingle: List<ListBean>, listDouble: List<ListBean>) {
        if (isAdd) {
            singleLineAdapter.addData(listSingle)
            doubleAdapter.addData(listDouble)
        } else {
            singleLineAdapter.setNewData(listSingle)
            doubleAdapter.setNewData(listDouble)
        }
    }

    private fun setOnItemListener(baseQuickAdapter: BaseQuickAdapter<ListBean, *>) {
        baseQuickAdapter.setOnItemClickListener { adapter, _, position ->
            val bean = adapter.getItem(position) as ListBean
            routerNavigation(path_hxd_product_detail_page, mutableMapOf(product_skuNo to bean.no))
            context?.sendPoint(commodity_click)
        }
    }

}